package com.example.padlock.data.common.httputil;

import java.util.Iterator;
import java.util.Map;

import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;

import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;

public class CookieUtil {

	private Context mContext;
	private SharedPreferences sp;
	private Editor edit;

	public CookieUtil() {

	}

	public CookieUtil(Context context) {
		this.mContext = context;
		sp = mContext.getSharedPreferences("cookie", Context.MODE_PRIVATE);
		edit = sp.edit();
	}

	/**
	 * 保存Cookie
	 * 
	 * @param resp
	 */
	public void SaveCookies(HttpResponse httpResponse) {
		org.apache.http.Header[] headers = httpResponse
				.getHeaders("Set-Cookie");
		String headerstr = headers.toString();
		if (headers == null)
			return;
		for (int i = 0; i < headers.length; i++) {
			String cookie = headers[i].getValue();
			String[] cookievalues = cookie.split(";");
			for (int j = 0; j < cookievalues.length; j++) {
				String[] keyPair = cookievalues[j].split("=");
				String key = keyPair[0].trim();
				String value = keyPair.length > 1 ? keyPair[1].trim() : "";
				edit.putString(key, value);
				edit.commit();
			}
		}
	}
	
	public void saveExtralValue(String key,String value){
		edit.putString(key, value);
		edit.commit();
	}

	/**
	 * 增加含有authkey的Cookie
	 * 
	 * @param request
	 */
	public void AddCookies(HttpPost request) {
		StringBuilder sb = new StringBuilder();
		Map<String, ?> cookieContainer = sp.getAll();
		Iterator<?> iterator = cookieContainer.entrySet().iterator();
		while (iterator.hasNext()) {
			Map.Entry entry = (Map.Entry) iterator.next();
			String key = entry.getKey().toString();
			String val = entry.getValue().toString();
			sb.append(key);
			sb.append("=");
			sb.append(val);
			sb.append(";");
		}
		System.out.println("cookie:"+sb.toString());
		request.addHeader("cookie", sb.toString());
	}
	
	public String getCookie(){
		StringBuilder sb = new StringBuilder();
		Map<String, ?> cookieContainer = sp.getAll();
		Iterator<?> iterator = cookieContainer.entrySet().iterator();
		while (iterator.hasNext()) {
			Map.Entry entry = (Map.Entry) iterator.next();
			String key = entry.getKey().toString();
			String val = entry.getValue().toString();
			sb.append(key);
			sb.append("=");
			sb.append(val);
			sb.append(";");
		}
		System.out.println("cookie:"+sb.toString());
		return sb.toString();
	}

}
